package com.zsinfo.guoss.supplier.activity;

import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.netcenter.Event.Response;
import com.example.netcenter.RetrofitBuilder;
import com.example.netcenter.Url.ConstantsCode;
import com.example.netcenter.bean.ErrorBean;
import com.example.netcenter.bean.RegisterBean;
import com.example.netcenter.bean.ResultsData;
import com.example.netcenter.bean.SystemConstantBean;
import com.google.gson.Gson;
import com.zsinfo.guoss.supplier.MainActivity;
import com.zsinfo.guoss.supplier.R;
import com.zsinfo.guoss.supplier.base.BaseActivity;
import com.zsinfo.guoss.supplier.logichelper.LoginAndRegisterHelper;
import com.zsinfo.guoss.supplier.utils.SharedPreferencesUtil;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by lixl on 2018/12/4.
 * <p>
 * desc: 手机号验证码登录界面
 */
public class LoginCodeActivity extends BaseActivity implements View.OnClickListener {

    private EditText et_account_phone, et_sms_code;
    private ImageView iv_account_phone_clean, iv_sms_code_clean;
    private TextView btn_send_code;
    private Button btn_login;
    private TextView btn_to_loginpwd;
    private TextView btn_agreement;

    private int time = 60;
    private MyCountDownTimer timer;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    setResult(RESULT_OK);
                    break;
                case 4:
                    btn_send_code.setEnabled(false);
                    btn_send_code.setText("已发送(" + String.valueOf(time) + ")");
                    break;
                case 5:
                    btn_send_code.setEnabled(true);
                    btn_send_code.setText("重新获取验证码");
                    time = 60;
                    break;
            }
        }
    };
    private String phone;
    private String code;

    @Override
    protected int getContentLayoutRes() {
        return R.layout.activity_login_code;
    }

    @Override
    protected void initView() {

        setTitle("登录");

        timer = new MyCountDownTimer(60000, 1000);

        et_account_phone = findViewById(R.id.et_account_phone);
        et_sms_code = findViewById(R.id.et_sms_code);
        iv_account_phone_clean = findViewById(R.id.iv_account_phone_clean);
        iv_sms_code_clean = findViewById(R.id.iv_sms_code_clean);
        btn_send_code = findViewById(R.id.btn_send_code);
        btn_login = findViewById(R.id.btn_login);
        btn_to_loginpwd = findViewById(R.id.btn_to_loginpwd);
        btn_agreement = findViewById(R.id.btn_agreement);

        et_account_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //编辑框的内容发生改变之前的回调方法
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //编辑框的内容正在发生改变时的回调方法 >>用户正在输入
                //我们可以在这里实时地 通过搜索匹配用户的输入
                if (s.toString().length() > 0){
                    iv_account_phone_clean.setVisibility(View.VISIBLE);
                } else {
                    iv_account_phone_clean.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                //编辑框的内容改变以后,用户没有继续输入时 的回调方法
            }
        });

        et_sms_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().length() > 0){
                    iv_sms_code_clean.setVisibility(View.VISIBLE);
                } else {
                    iv_sms_code_clean.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        iv_account_phone_clean.setOnClickListener(this);
        iv_sms_code_clean.setOnClickListener(this);
        btn_send_code.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        btn_to_loginpwd.setOnClickListener(this);
        btn_agreement.setOnClickListener(this);
    }

    @Override
    protected void initNetData() {
        
    }

    @Override
    protected void customDestroy() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_account_phone_clean:
                //清除输入的账号
                et_account_phone.setText("");
                break;
            case R.id.iv_sms_code_clean:
                //清除输入的密码
                et_sms_code.setText("");
                break;
            case R.id.btn_send_code:
                phone = et_account_phone.getText().toString().trim();
                if (TextUtils.isEmpty(phone)){
                    showToast("请输入手机号");
                    return;
                }
                sendSMSCode(phone);
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        time--;
                        if (time <= 0) {
                            mHandler.sendEmptyMessage(5);
                        } else {
                            mHandler.sendEmptyMessage(4);
                            mHandler.postDelayed(this, 1000);
                        }
                    }
                };
                new Thread(runnable).start();
                break;
            case R.id.btn_login:
                phone = et_account_phone.getText().toString().trim();
                code = et_sms_code.getText().toString().trim();
                if (TextUtils.isEmpty(phone)){
                    showToast("请输入手机号");
                    return;
                }
                if (TextUtils.isEmpty(code)){
                    showToast("请输入验证码");
                    return;
                }
                verifySMSCode(phone, code);
                break;
            case R.id.btn_to_loginpwd:
                startActivity(new Intent(this, LoginPwdActivity.class));
                break;
            case R.id.btn_agreement:
                startActivity(new Intent(this, AgreementActivity.class));
                break;
        }
    }

    //倒计时函数
    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            btn_send_code.setClickable(false);
            btn_send_code.setText(l/1000+"秒");
        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            btn_send_code.setText("重新获取");
            //设置可点击
            btn_send_code.setClickable(true);
        }
    }

    /**
     * 发送短信验证码:
     * @param phone
     */
    private void sendSMSCode(String phone){
        GetNetCenter().GetNetCenter(
                RetrofitBuilder.CreateApi().SENDSMS(ConstantsCode.gss_sms, phone), new Response() {
                    @Override
                    public void OK(Object data) {
                        Log.e("lixl", data.toString());
                        showToast("发送成功");
                    }

                    @Override
                    public void Fail(Throwable e) {
                        Log.e("lixl", e.getMessage());
                        if (e.getMessage().contains("Code")) {
                            ErrorBean errorBean = new Gson().fromJson(e.getMessage(), ErrorBean.class);
                            showToast(errorBean.getMsg());
                        } else {
                            showToast(e.getMessage());
                        }
                    }

                    @Override
                    public void complete() {

                    }
                });
    }

    /**
     * 验证验证码是否正确
     * @param phone
     * @param code
     */
    private void verifySMSCode(String phone, String code){
        GetNetCenter().GetNetCenter(this,
                RetrofitBuilder.CreateApi().VERIFYSMSCODE(ConstantsCode.supplier_dynamic_login, phone, code), new Response() {
                    @Override
                    public void OK(Object data) {
                        Log.e("lixl", data.toString());
                        showToast("验证成功");
                        getSysMes();
                        RegisterBean registerBean = (RegisterBean) data;
                        LoginAndRegisterHelper loginAndRegisterHelper = new LoginAndRegisterHelper();
                        loginAndRegisterHelper.SaveInfo(registerBean);
                        startActivity(new Intent(LoginCodeActivity.this, MainActivity.class));
                        JPushInterface.setAlias(LoginCodeActivity.this, 1, SharedPreferencesUtil.getFirmMobile()+"");  //设置别名
                        finish();
                    }

                    @Override
                    public void Fail(Throwable e) {
                        Log.e("lixl", e.getMessage());
                        if (e.getMessage().contains("Code")) {
                            ErrorBean errorBean = new Gson().fromJson(e.getMessage(), ErrorBean.class);
                            String errorCode = errorBean.getCode();
                            String errorDesc = errorBean.getMsg();
                            if (errorCode.equals("100500")) {
                                startActivity(new Intent(LoginCodeActivity.this, RegisteredActivity.class));
                            }
                            showToast(errorDesc);

                        } else {
                            showToast(e.getMessage());
                        }
                    }

                    @Override
                    public void complete() {

                    }
                });
    }

    private void getSysMes() {
        GetNetCenter().GetNetCenter(RetrofitBuilder.CreateApi().SYSTEM_CONFIG_CONSTANT(
                ConstantsCode.system_config_constant,
                SharedPreferencesUtil.getWebsiteNode()),
                new Response() {
                    @Override
                    public void OK(Object data) {
                        Log.e("lixl", data.toString());
                        ResultsData<SystemConstantBean> resultsData = (ResultsData<SystemConstantBean>) data;
                        SystemConstantBean systemConstantBean = resultsData.getData();
                        SharedPreferencesUtil.setALiPayAppId(systemConstantBean.getAlipay_app_id_new());
                        SharedPreferencesUtil.setALiPay_RSA_Private(systemConstantBean.getAlipay_rsa_private_new());
                        SharedPreferencesUtil.setALiPay_RSA_Public(systemConstantBean.getAlipay_rsa_alipay_public_new());
                    }

                    @Override
                    public void Fail(Throwable e) {
                        Log.e("lixl", e.getMessage());
                        if (!e.getLocalizedMessage().contains("100000") && e.getLocalizedMessage().contains("Code")) {
                            ErrorBean errorBean = new Gson().fromJson(e.getMessage(), ErrorBean.class);
                            showToast(errorBean.getMsg());
                        }
                    }

                    @Override
                    public void complete() {

                    }
                });
    }
}
